<template>
  <div>
    <!-- 用户信息列表 修改用户信息 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="dialogFormVisible">
      <el-form v-model="selectedUser" style="text-align: left" ref="dataForm">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <label>{{selectedUser.username}}</label>
        </el-form-item>
        <el-form-item label="真实姓名" label-width="120px" prop="name">
          <el-input v-model="selectedUser.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="120px" prop="phone">
          <el-input v-model="selectedUser.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px" prop="email">
          <el-input v-model="selectedUser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-button type="warning" @click="resetPassword(selectedUser.username)">重置密码</el-button>
        </el-form-item>
        <el-form-item label="角色分配" label-width="120px" prop="roles">
          <el-checkbox-group v-model="selectedRolesIds" :max="1">
              <el-checkbox v-for="(role,i) in roles" :key="i" :label="role.id">
                   {{role.nameZh}}
                </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit(selectedUser)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 按钮上面的导航 -->
    <!-- <el-row style="margin: 18px 0px 0px 18px "> -->
    <el-row>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/admin/dashboard' }">管理中心</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户信息</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <!-- 搜索与添加按钮 -->
    <div style="margin-top: 15px; margin-left: 12px;">
      <el-input  placeholder="请输入用户名" v-model="queryKey3" style="width: 530px;float:left;"  clearable>
        <el-select v-model="queryKey1" style="width: 150px;" slot="prepend" placeholder="请选择身份">
          <el-option label="" value=""></el-option>
          <el-option label="管理员" value="0"></el-option>
          <el-option label="学生" value="1"></el-option>
          <el-option label="老师" value="2"></el-option>
        </el-select>
         <el-select v-model="queryKey2" style="width: 130px;" slot="prepend" placeholder="请选择状态">
           <el-option label="" value=""></el-option>
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <!-- <el-button slot="append" type="primary" icon="el-icon-search" @click="findByQueryKey()"></el-button> -->
      </el-input>
      <el-button style="float:left;" type="primary" @click="findByQueryKey()" icon="el-icon-search">搜索</el-button>
      <div style="float:left;"><bulk-registration @onSubmit="listUsers()"></bulk-registration></div>
    </div>
    <el-card style="margin: 15px 1%;width: 98%">
      <el-table
        :data="users"
        border
        :default-sort = "{prop: 'id', order: 'ascending'}"
        style="width: 100%"
        :max-height="tableHeight">
        <el-table-column
          prop="id"
          label="id"
          sortable
          width="60">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          fit>
        </el-table-column>
        <el-table-column
          prop="name"
          label="真实姓名"
          fit>
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          fit>
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          show-overflow-tooltip
          fit>
        </el-table-column>

        <el-table-column
          prop="identity"
          label="身份"
          sortable
          width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.identity === 0">
              <el-tag type="danger">管理员</el-tag>
            </div>
            <div v-if="scope.row.identity === 1">
              <el-tag type="success">学生</el-tag>
            </div>
            <div v-if="scope.row.identity === 2">
              <el-tag type="warning">老师</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="启用"
          sortable
          width="110">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="(value) => commitStatusChange(value, scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120">
          <template slot-scope="scope">
            <el-button
              @click="editUser(scope.row)"
              type="primary"
              size="small"
              icon="el-icon-edit" circle>
            </el-button>
            <el-button
            @click="deleteUser(scope.row)"
              type="danger"
              size="small"
              icon="el-icon-delete" circle>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
  </div>
</template>

<script>
  import BulkRegistration from './BulkRegistration'
    export default {
      name: 'UserProfile',
      components: {BulkRegistration},
      data () {
          return {
            users: [],
            roles: [],
            dialogFormVisible: false,
            selectedUser: [],
            selectedRolesIds: [],
            queryKey1: '',
            queryKey2: '',
            queryKey3: ''
          }
      },
      mounted () {
        this.listUsers()
        this.listRoles()
      },
      computed: {
        tableHeight () {
          return window.innerHeight - 240
        }
      },
      methods: {
        listUsers () {
          var _this = this
          this.$axios.get('/admin/user').then(resp => {
            if (resp && resp.data.code === 200) {
              _this.users = resp.data.result
            }
          })
        },
        listRoles () {
          var _this = this
          this.$axios.get('/admin/roleByUser').then(resp => {
            if (resp && resp.data.code === 200) {
              _this.roles = resp.data.result
            }
          })
        },
        commitStatusChange (value, user) {
          if (user.username !== 'admin') {
            this.$axios.put('/admin/user/status', {
              enabled: value,
              username: user.username
            }).then(resp => {
              if (resp && resp.data.code === 200) {
                if (value) {
                  this.$message('用户 [ ' + user.username + ' ] 已启用')
                } else {
                  this.$message('用户 [ ' + user.username + ' ] 已禁用')
                }
              }
            })
          } else {
            user.enabled = true
            this.$alert('不能禁用管理员账户')
          }
        },
        onSubmit (user) {
          let _this = this
          // 根据视图绑定的角色 id 向后端传送角色信息
          let roles = []
          for (let i = 0; i < _this.selectedRolesIds.length; i++) {
            for (let j = 0; j < _this.roles.length; j++) {
              if (_this.selectedRolesIds[i] === _this.roles[j].id) {
                roles.push(_this.roles[j])
              }
            }
          }
          this.$axios.put('/admin/user', {
            username: user.username,
            name: user.name,
            phone: user.phone,
            email: user.email,
            roles: roles
          }).then(resp => {
            if (resp && resp.data.code === 200) {
              this.$alert('用户信息修改成功')
              this.dialogFormVisible = false
              // 修改角色后重新请求用户信息，实现视图更新
              this.listUsers()
            } else {
              this.$alert(resp.data.message)
            }
          })
        },
        editUser (user) {
          this.dialogFormVisible = true
          this.selectedUser = user
          let roleIds = []
          for (let i = 0; i < user.roles.length; i++) {
            roleIds.push(user.roles[i].id)
          }
          this.selectedRolesIds = roleIds
        },
        resetPassword (username) {
          this.$axios.put('/admin/user/password', {
            username: username
          }).then(resp => {
            if (resp && resp.data.code === 200) {
              this.$alert('密码已重置为 0774123')
          }
          })
        },
        deleteUser (user) {
          if (user.username !== 'admin') {
            this.$confirm('此操作将永久删除该用户 ' + user.id + ', 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                this.$axios
                  .post('/admin/user/del?id=' + user.id).then(resp => {
                  if (resp && resp.data.code === 200) {
                    this.listUsers()
                  }
                })
              }
            ).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
            } else {
          this.$alert('不能删除管理员账户')
        }
      },
      findByQueryKey () { // 根据关键字查询
          var _this = this
          this.$axios.post('/admin/user/findByQueryKey?queryKey1=' + this.queryKey1 + '&queryKey2=' + this.queryKey2 + '&queryKey3=' + this.queryKey3).then(resp => {
            if (resp && resp.data.code === 200) {
              _this.users = resp.data.result
              // 从后端返回信息
              this.$alert(resp.data.message, '提示', {
                type: 'success',
                dangerouslyUseHTMLString: true
              })
            }
          })
        }
      }
    }
</script>

<style scoped>

</style>
